package cn.zeal4j.handler;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @file Spring-Security-Tutorial
 * @create 2020 09 28 14:37
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");

        PrintWriter printWriter = httpServletResponse.getWriter();
        // json数据 ： { "status" : "error" , "message" : "权限不足，访问被禁止！！！" }
        printWriter.print("{ \"status\" : \"error\" , \"message\" : \"权限不足，访问被禁止！！！\" }");
        printWriter.flush();
        printWriter.close();
    }
}
